<template>

  <div id="codeEditorContain" ref="codeContainRef" style="min-height: 300px;"/>
</template>

<script setup lang="ts">
import {defineProps, onMounted, ref, toRaw, watch, withDefaults} from "vue";
import * as monaco from "monaco-editor";

/***
 * 接收父组件传值的接口
 */
interface Props {
  value: string;
  handleChange: (v: string) => void;
  language?: string;
  handleLanguage:(v:string)=>void;
}

/**
 * 如果父组件没有传值，就会给一个默认值
 */
const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  handleChange: (v: string) => {
  },
  language: () => "java",
  handleLanguage:(v:string)=>{}
})
const codeContainRef = ref()//代码容器实例
const codeEditor = ref();



//挂载初始化钩子
onMounted(() => {
  if (!codeContainRef.value) {
    return;//如果实例为空  不执行任何操作
  }
  codeEditor.value = monaco.editor.create(codeContainRef.value, {
    value: props.value,
    language: props.language,
    automaticLayout: true,
    colorDecorators: true,
    minimap: {
      enabled: true,
    },
    readOnly: false,
    theme: "vs-dark",
    // lineNumbers: "off",
    // roundedSelection: false,
    // scrollBeyondLastLine: false,
  });
  //监听代码内容变化
  codeEditor.value.onDidChangeModelContent(() => {

    // $emit('handleChangeCode',toRaw(codeEditor.value).getValue())
    props.handleChange(toRaw(codeEditor.value).getValue())
  })
})

/**
 * 监听pros.language 的变化  触发监听器
 */
watch(()=>props.language,()=>{

  if(codeEditor.value){
    monaco.editor.setModelLanguage(toRaw(codeEditor.value).getModel(),props.language)
  }

})

</script>

<style scoped>

</style>